
package com.bj58.disconf.web.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bj58.disconf.web.PrintBeat;
import com.bj58.disconf.web.common.constraint.validation.PageOrderValidator;
import com.bj58.disconf.web.common.exception.DocumentNotFoundException;
import com.bj58.disconf.web.common.utils.ParamUtil;
import com.bj58.disconf.web.common.vo.JsonObjectBase;
import com.bj58.disconf.web.controllers.config.validator.ConfigValidator;
import com.bj58.disconf.web.service.config.form.ConfListForm;
import com.bj58.disconf.web.service.config.form.VersionListForm;
import com.bj58.disconf.web.service.config.service.ConfigMgr;
import com.bj58.disconf.web.service.config.vo.ConfListVo;
import com.bj58.disconf.web.service.config.vo.MachineListVo;
import com.bj58.disconf.web.utils.GuiceDI;
import com.bj58.disconf.web.utils.TarUtils;
import com.bj58.ub.common.db.DaoPageResult;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.annotation.Path;

/**
 * 专用于配置读取
 *
 * @author lemon
 * @version 2014-6-22
 */
@Path("/api/web/config")
public class ConfigReadController extends BaseController {

    protected static final Logger LOG = LoggerFactory.getLogger(ConfigReadController.class);

    private final ConfigMgr configMgr = GuiceDI.getInstance(ConfigMgr.class);

    private final ConfigValidator configValidator = GuiceDI.getInstance(ConfigValidator.class);

    /**
     * 获取版本的List
     *
     * @return
     */
    @RequestMapping(value = "/versionlist", method = RequestMethod.GET)
    @ResponseBody
    @Path("/versionlist")
    public ActionResult getVersionList() {
        try {
            PrintBeat.printBeat(beat);

            long appid = ParamUtil.getLong(beat.getRequest(), "appId", -1l);
            long envId = ParamUtil.getLong(beat.getRequest(), "envId", -1l);
            
            List<String> versionList = configMgr.getVersionListByAppEnv(appid, -1 == envId ? null : envId);

            return new JsonActionResult(buildListSuccess(versionList, versionList.size()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取列表,有分页的
     *
     * @param confListForm
     *
     * @return
     */
    @Path("/list")
    public ActionResult getConfigList(@Valid ConfListForm confListForm) {

        try {
            PrintBeat.printBeat(beat);

            // 设置排序方式
            confListForm.getPage().setOrderBy("name");
            confListForm.getPage().setOrder(PageOrderValidator.ASC);

            DaoPageResult<ConfListVo> configs = configMgr.getConfigList(confListForm, true, false);

            return new JsonActionResult(buildListSuccess(configs));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取列表,有分页的, 没有ZK信息
     *
     * @param confListForm
     *
     * @return
     */
    @Path("/simple/list")
    public ActionResult getSimpleConfigList(@Valid ConfListForm confListForm) {

        PrintBeat.printBeat(beat);

        // 设置排序方式
        try {
            confListForm.getPage().setOrderBy("name");
            confListForm.getPage().setOrder(PageOrderValidator.ASC);

            DaoPageResult<ConfListVo> configs = configMgr.getConfigList(confListForm, false, false);

            return new JsonActionResult(buildListSuccess(configs));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取某个
     *
     * @param configId
     *
     * @return
     */
    @RequestMapping(value = "/{configId}", method = RequestMethod.GET)
    @ResponseBody
    @Path("/{configId}")
    public ActionResult getConfig(@PathVariable long configId) {
        try {
            PrintBeat.printBeat(beat);
            // 业务校验
            configValidator.valideConfigExist(configId);

            ConfListVo config = configMgr.getConfVo(configId);

            return new JsonActionResult(buildSuccess(config));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 zk
     *
     * @param configId
     *
     * @return
     */
    @RequestMapping(value = "/zk/{configId}", method = RequestMethod.GET)
    @ResponseBody
    @Path("/zk/{configId}")
    public ActionResult getZkInfo(@PathVariable long configId) {
        try {
            PrintBeat.printBeat(beat);
            // 业务校验
            configValidator.valideConfigExist(configId);

            MachineListVo machineListVo = configMgr.getConfVoWithZk(configId);

            return new JsonActionResult(buildSuccess(machineListVo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载
     *
     * @param configId
     *
     * @return
     */
    @RequestMapping(value = "/download/{configId}", method = RequestMethod.GET)
    @Path("/download/{configId}")
    public HttpEntity<byte[]> downloadDspBill(@PathVariable long configId) {

        try {
            PrintBeat.printBeat(beat);
            // 业务校验
            configValidator.valideConfigExist(configId);

            ConfListVo config = configMgr.getConfVo(configId);

            HttpHeaders header = new HttpHeaders();
            byte[] res = config.getValue().getBytes();
            if (res == null) {
                throw new DocumentNotFoundException(config.getKey());
            }

            String name = null;

            name = URLEncoder.encode(config.getKey(), "UTF-8");

            header.set("Content-Disposition", "attachment; filename=" + name);
            header.setContentLength(res.length);
            return new HttpEntity<byte[]>(res, header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 批量下载配置文件
     *
     * @param confListForm
     *
     * @return
     */
    @RequestMapping(value = "/downloadfilebatch", method = RequestMethod.GET)
    @Path("/downloadfilebatch")
    public HttpEntity<byte[]> download2(@Valid ConfListForm confListForm) {

        LOG.info(confListForm.toString());

        //
        // get files
        //
        List<File> fileList = configMgr.getDisconfFileList(confListForm);

        //
        // prefix
        //
        String prefixString = "APP" + confListForm.getAppId() + "_" + "ENV" + confListForm.getEnvId() + "_" + "VERSION" + confListForm.getVersion();

        HttpHeaders header = new HttpHeaders();

        String targetFileString = "";
        File targetFile = null;
        byte[] res = null;
        try {
            targetFileString = TarUtils.tarFiles("tmp", prefixString, fileList);
            targetFile = new File(targetFileString);
            res = IOUtils.toByteArray(new FileInputStream(targetFile));
        } catch (Exception e) {
            throw new DocumentNotFoundException("");
        }

        header.set("Content-Disposition", "attachment; filename=" + targetFile.getName());
        header.setContentLength(res.length);
        return new HttpEntity<byte[]>(res, header);
    }
}
